import 'package:cave_flutter/model/base_source_model.dart';
import 'package:cave_flutter/network/whl_api.dart';
import 'package:cave_flutter/pages/whl_mine/medal_wall/medal_wall_detail_view.dart';
import 'package:cave_flutter/routes/whl_app_pages.dart';
import 'package:cave_flutter/utils/task_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class MedalWallLogic extends GetxController
    with GetSingleTickerProviderStateMixin {
  late TabController tabController;
  int selectedIndex = 0;
  //  已解锁
  List<MedalModel> unlockWall = [];
  //  自动解锁
  List<MedalModel> automaticWall = [];
  //  手动解锁
  List<MedalModel> handWall = [];
  int haveMedalCount = 0;
  int medalCount = 0;
  MedalModel? selectedMedal;
  String? ranking = "0%";
  @override
  void onInit() {
    super.onInit();
    TaskUtils.complateTask(14, type: 2);
    tabController = TabController(
      length: 3,
      vsync: this,
      initialIndex: selectedIndex,
    );

    automaticWall = [];
    handWall = [];
    getList();
  }

  getList() {
    // /app/user-medal/getMedalList
    WhlApi.getMedalList.get(({})).then((value) {
      if (value.isSuccess()) {
        ranking = value.data['ranking'];
        haveMedalCount = value.data['haveMedalCount'];
        medalCount = value.data['medalCount'];
        unlockWall = List<MedalModel>.from(
            value.data['havaList'].map((c) => MedalModel.fromJson(c))).toList();
        automaticWall = List<MedalModel>.from(
            value.data['autoList'].map((c) => MedalModel.fromJson(c))).toList();

        handWall = List<MedalModel>.from(
            value.data['handList'].map((c) => MedalModel.fromJson(c))).toList();

        update();
      }
    });
  }

  selectMedal(MedalModel data) {
    if (selectedMedal != data) {
      selectedMedal = data;
    } else {
      selectedMedal = null;
    }
    update();
  }

  useMedal(MedalModel data) {
    data.wearing = !(data.wearing == true);
    WhlApi.wearingMedal.post({
      'medalId': data.id,
      'wearing': data.wearing == true ? 1 : 0,
    }).then((res) {
      update();
    });
  }

  goDetail(MedalModel data) {
    Get.to(MedalWallDetailPage(
      data: data,
    ));
  }
}

class MedalModel {
  String? userId;
  String? id;
  String? medalName;
  String? imageUrl;
  //  0 手动 1自动
  String? unlockType;
  String? describe;
  String? haveTime;
  bool? wearing;

  MedalModel({
    this.userId,
    this.id,
    this.medalName,
    this.imageUrl,
    this.unlockType,
    this.describe,
    this.haveTime,
    this.wearing,
  });

  MedalModel.fromJson(Map<String, dynamic> json) {
    userId = json['userId'];
    id = json['id'];
    medalName = json['medalName'];
    imageUrl = json['imageUrl'];
    unlockType = json['unlockType'];
    describe = json['describe'];
    haveTime = json['haveTime'];
    wearing = json['wearing'];
  }
}
